/*
 * @Description: user 模型类
 * @Author: Junhuang
 * @Date: 2022-02-08 15:54:31
 * @LastEditTime: 2022-02-15 21:42:16
 * @LastEditors: Junhuang
 * @Reference: 
 */
'use strict';
// 引入
const crypto = require('crypto');
module.exports = app => {
  const { INTEGER, STRING, DATE, ENUM, TEXT } = app.Sequelize;
  // 配置（重要：一定要配置详细，一定要！！！）
  const User = app.model.define('user', {
    id: { type: INTEGER(20), primaryKey: true, autoIncrement: true, comment: '主键id' },
    username: { type: STRING(30), allowNull: false, defaultValue: '', comment: '用户名称', unique: true },
    nickname: { type: STRING(30), allowNull: false, defaultValue: '', comment: '昵称' },
    email: { type: STRING(160), allowNull: false, defaultValue: '', comment: '电子邮箱' },
    password: {
      type: STRING, allowNull: false, defaultValue: '', comment: '密码',
      set(val) {
        const hmac = crypto.createHash('sha256', app.config.crypto.secret);
        hmac.update(val);
        this.setDataValue('password', hmac.digest("hex"));
      }
    },
    avatar: { type: STRING, allowNull: true, defaultValue: '', comment: '头像' },
    phone: { type: STRING(11), allowNull: false, defaultValue: '', comment: '手机' },
    sex: { type: ENUM, values: ['男', '女', '保密'], allowNull: false, defaultValue: '男', comment: '性别' },
    description: { type: TEXT, allowNull: false, defaultValue: '', comment: '个性签名' },
    created_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('created_time')
        return (new Date(val)).getTime()
      }
    },
    updated_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('updated_time')
        return (new Date(val)).getTime()
      }
    }
  }, {
    timestamps: true, // 是否自动写入时间戳
    tableName: 'user', // 自定义数据表名称
  });

  return User;
};